<template>
  <el-form ref="formEl" label-position="top" :model="form" :rules="rules">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="性别">
      <el-radio-group v-model="form.gender">
        <el-radio label="1">男</el-radio>
        <el-radio label="0">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="邮箱" v-model="form.email" prop="email">
      <el-input v-model="form.email" />
    </el-form-item>
    <el-form-item label="手机" v-model="form.phone" prop="phone">
      <el-input v-model="form.phone" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button type="info" link @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import { updateUserByIdApi, checkUsersExistApi, getUserByIdApi } from '@/api/users';

const props = defineProps(['id']);
const emits = defineEmits(['save', 'cancel']);

const userInfo = ref({});

// 绑定数据
const form = reactive({
  username: '',
  gender: '1',
  email: '',
  phone: '',
});

const formEl = ref(null);

//  获取用户信息

async function getUserById() {
  const { data } = await getUserByIdApi(props.id);
  userInfo.value = data;
  form.username = data.username;
  form.phone = data.phone;
  form.gender = data.gender;
  form.email = data.email;
}

// 根据id的变化请求用户数据
watch(
  () => props.id,
  async () => {
    await getUserById();
  },
  {
    immediate: true,
  },
);

function check(reg, message) {
  return (rule, value, cb) => {
    if (typeof reg === 'function' ? reg(value) : reg.test(value)) {
      cb();
    } else {
      cb(new Error(message));
    }
  };
}

function remoteCheck(field, message) {
  return async (rule, value, cb) => {
    if (value === '' || value === userInfo.value[field]) {
      cb();
    } else {
      const res = await checkUsersExistApi(field, value);
      if (res.data) {
        cb(new Error(message));
      } else {
        cb();
      }
    }
  };
}

const emailReg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
// 验证规则
const rules = reactive({
  username: [
    { required: true, message: '用户名必须填写', trigger: 'change' },
    { validator: check(/^\w{2,18}$/, '用户名2-18位'), trigger: 'change' },
    { validator: remoteCheck('username', '用户名已经存在'), trigger: 'blur' },
  ],
  email: [
    { required: true, message: '邮箱必须填写', trigger: 'change' },
    { validator: check(emailReg, '邮箱格式非法'), trigger: 'change' },
    { validator: remoteCheck('email', '邮箱已经存在'), trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '手机必须填写', trigger: 'change' },
    { validator: check(/^(?:(?:\+|00)86)?1\d{10}$/, '手机格式非法'), trigger: 'change' },
    { validator: remoteCheck('phone', '手机已经存在'), trigger: 'blur' },
  ],
});

// 保存
async function handleSave() {
  // console.log('handleSave');
  // 表单验证
  await formEl.value.validate();
  // 排除未修改的值
  const data = Object.entries(form).reduce((obj, el) => {
    if (el[1] !== userInfo[el[0]]) {
      // eslint-disable-next-line no-param-reassign, prefer-destructuring
      obj[el[0]] = el[1];
    }
    return obj;
  }, {});
  // 调用接口
  await updateUserByIdApi(props.id, data);
  // 触发保存事件
  emits('save');
}

function handleCancel() {
  // 触发保存事件
  emits('cancel');
}
</script>
